package site.wanjiahao.client;

import java.io.*;
import java.nio.charset.StandardCharsets;

import static java.nio.charset.StandardCharsets.UTF_8;

/**
 * 获取文件流
 */
public class FetchFileHttpRequest extends HttpGet {

    private final File file;

    // 重写字段，因为响应是流类型
    public static final String STREAM_CONTEXT_TYPE = "application/octet-stream;charset=utf-8";
    
    public FetchFileHttpRequest(String storePath, String url) throws IOException {
        this(new File(storePath), url);
    }

    public FetchFileHttpRequest(File file, String url) throws IOException {
        this.file = file;
        this.url = url;
        this.contextType = STREAM_CONTEXT_TYPE;
    }
    
    @Override
    protected void handler() throws IOException {
        String headerField = getHeaderField("Content-Disposition");
        // 编码转换
        String filename = headerField.substring(headerField.lastIndexOf("=") + 1);
        filename = new String(filename.getBytes(StandardCharsets.ISO_8859_1),
                UTF_8);

        BufferedInputStream in = new BufferedInputStream(getInputStream());

        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file + "/" + filename));

        byte[] bytes = new byte[1024];
        int len;
        while ((len = in.read(bytes)) != -1) {
            out.write(bytes, 0, len);
            out.flush();
        }
        System.out.println(1);
        out.close();
    }

}
